package com.fuyun.microservice.controller;

import com.alibaba.fastjson.JSON;
import com.fuyun.microservice.ResultObject;
import com.fuyun.microservice.codec.msg.BroadRequestMessage;
import com.fuyun.microservice.connect.BroadMessageAdaptor;
import com.fuyun.microservice.connect.SessionStore;
import com.fuyun.microservice.gate.api.BroadcastMessageApi;
import com.fuyun.microservice.gate.model.broadcast.BroadcastPushRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@Slf4j
public class BroadcastController implements BroadcastMessageApi {
    private final BroadMessageAdaptor broadMessageAdaptor;
    private final SessionStore sessionStore;

    public BroadcastController(BroadMessageAdaptor broadMessageAdaptor, SessionStore sessionStore) {
        this.broadMessageAdaptor = broadMessageAdaptor;
        this.sessionStore = sessionStore;
    }


    @Override
    public ResultObject push(@Valid @RequestBody BroadcastPushRequest request) {
        log.info("boardmessage body:{}", JSON.toJSONString(request));
        BroadRequestMessage broadRequestMessage = new BroadRequestMessage();
        broadRequestMessage.setType(request.getType());
        broadRequestMessage.setShouldAck(request.getShouldAck());
        broadRequestMessage.setTopic(request.getTopic());
        broadRequestMessage.setBody(request.getBody());

        broadMessageAdaptor.broad(broadRequestMessage);

        return ResultObject.buildSuccess();
    }

    @GetMapping("clients")
    public Object clients(){
        return sessionStore.all();
    }
}
